App({
  data: {},
  globalData: {
    openid: '',
    myselfflag:true,
    appid: 'wxd0cc4487685bcf08',
    secret: 'c375796cd0e2393a1cdad053a0d3b786',
    dormitoryId:0,
    count: 1,
  },
  onLaunch: function (options) {
    const self = this; 
    wx.cloud.init({
      traceUser: true,
      env: 'cloud1-2g8f38dt91111a5c',
    });
    // 云函数调用
      wx.cloud.callFunction({
        name: 'login',
        data: {}
      }).then(res => {
        this.globalData.openid = res.result.openid;
        const nickname = "用户的昵称";
        const db = wx.cloud.database();
        const userCollection = db.collection('userInfo');
        const dormitoryCollection = db.collection('dormitory');
        dormitoryCollection.get().then(res => {
          this.globalData.count = parseInt(res.data.length) + 1;
          return userCollection.where({
            openid: this.globalData.openid
          }).get();
      }).then(res => {  
        if (res.data.length === 0) {
          this.globalData.dormitoryId = this.globalData.count;
          userCollection.add({
            data: {
              openid: this.globalData.openid,
              name: nickname,
              avatar: '/images/home/me.jpg',
              dormitoryId: this.globalData.dormitoryId
            }
          }).then(res => {
            console.log('用户初始化添加成功', res);

            const dormitoryCollection = db.collection('dormitory');
            return dormitoryCollection.add({
              data: {
                dormitoryId: this.globalData.dormitoryId,
                name: '你的宿舍',
                avatar: '/images/home/we.jpg',
                member: [{
                  "openid": this.globalData.openid,
                  "name": nickname
                }]
              }
            });
          }).then(res => {
            console.log('宿舍初始化添加成功', res);

            // 处理带参数的情况
            if (options.query && options.query.dormitoryId) {
              const dormitoryCollection = db.collection('dormitory');
              const _dormitoryId = parseInt(options.query.dormitoryId);

              userCollection.where({
                openid: this.globalData.openid
              }).get().then(res => {
                const friendData = res.data[0];
                this.globalData.dormitoryId = friendData.dormitoryId;
              });

              dormitoryCollection.where({
                dormitoryId: this.globalData.dormitoryId
              }).remove().then(res => {
                console.log('朋友自己的宿舍信息删除成功', res);
              }).catch(err => {
                console.error('朋友自己的宿舍信息删除失败', err);
              }).then(res => {
                userCollection.where({
                  openid: this.globalData.openid
                }).update({
                  data: {
                    dormitoryId: _dormitoryId
                  }
                }).then(res => {
                  console.log('分享后用户的宿舍修改成功', res);
                  this.globalData.dormitoryId = _dormitoryId;
                }).catch(err => {
                  console.error('查询用户宿舍失败', err);
                });
              }).then(res => {
                const db = wx.cloud.database();
                db.collection('dormitory').where({
                  dormitoryId: _dormitoryId
                }).get().then(res => {
                  if (res.data.length > 0) {
                    const _id = res.data[0]._id;
                    return wx.cloud.callFunction({
                      name: 'addMemberToDormitory',
                      data: {
                        _id: _id,
                        openid: this.globalData.openid,
                        name: nickname
                      }
                    });
                  } else {
                    throw new Error('未找到对应的宿舍记录');
                  }
                }).then(res => {
                  console.log('分享后宿舍用户添加成功', res);
                }).catch(err => {
                  console.error('分享后宿舍用户添加失败', err);
                });
              }).catch(err => {
                console.error('宿舍初始化添加失败', err);
              });
            }
          }).catch(err => {
            console.error('初始化用户信息失败', err);
          });
        }else{
          this.globalData.dormitoryId =res.data[0].dormitoryId;
        }
      }).catch(err => {
        console.error('获取用户OpenID失败', err);
      });
    })

  },
});